// mqttService.js
import mqtt from './mqtt4.1.0.js';
import getdateTime from './getdateTime.js';

class MqttService {
  constructor(options) {
    // 默认配置选项
    this.options = {
      host: 'mk-iot.com',
      wsport: '8083',
      wssport: '443',
      path: '/ws/',
      onTopic: 'test',
      onSub: 'SERVER.99999998.0DD7D9967724BE94',
      Qos: 2,
      clientIdPrefix: 'mqtt_',
      protocolVersion: 5,
      keepalive: 3,
      clean: false,
      username: 'test',
      password: 'root',
      reconnectPeriod: 1000,
      connectTimeout: 3000,
      resubscribe: true,
      reconnectCounter: 0,
      ...options, // 允许传入自定义配置覆盖默认值
    };

    this.client = null;
    this.isConnected = false;
  }

  init() {
    const clientId = `${this.options.clientIdPrefix}${Math.random().toString(16).substr(2, 8)}`;
    this.options.clientId = clientId;

    this.client = mqtt.connect(this.getHost(), this.options);
    this.setupEventHandlers();
  }

  setupEventHandlers() {
    const that = this;

    this.client.on('connect', () => {
      uni.hideLoading();
      uni.showToast({ title: '连接成功', icon: 'success' });
      that.isConnected = true;
      console.log('打印客户端实例', that.client);
      that.subscribe(that.options.onTopic);
    });

    this.client.on('message', (topic, message) => {
      console.log(`收到来自${topic}的消息${message.toString()}`);
      uni.$emit('mqttMessageReceived', { topic, message: message.toString() });
    });

    this.client.on('reconnect', (error) => {
      uni.hideLoading();
      uni.showToast({ title: '正在重连···', duration: 1000 });
      if (that.options.reconnectCounter === 0) {
        const nowTime = getdateTime.getNowTime();
        console.log('刚开始记录的时间', nowTime);
      }
      that.options.reconnectCounter++;
      console.log(`第${that.options.reconnectCounter}次重连`);

      if (that.options.reconnectCounter >= 3) {
        console.log('已经尝试了3次重连，现在断开连接');
        that.client.end();
        const endTime = getdateTime.getNowTime();
        console.log('结束时间 ', endTime);
        that.options.reconnectCounter = 0;
      }
    });

    this.client.on('error', (error) => {
      uni.hideLoading();
      uni.showToast({ title: '连接失败!', duration: 1000 });
    });
  }

  subscribe(topic) {
    if (!this.client || !this.client.connected) {
      uni.showToast({ title: '客户端未连接', duration: 1000 });
      return;
    }

    this.client.subscribe(topic, { qos: this.options.Qos }, (error) => {
      if (!error) {
        uni.showToast({ title: '订阅成功', icon: 'success' });
        console.log('订阅成功');
      }
    });
  }

  publish(topic, message) {
    if (!this.client || !this.client.connected) {
      uni.showToast({ title: '客户端未连接', duration: 1000 });
      return;
    }
    if (message != '') {
      this.client.publish(topic, JSON.stringify(message), (error) => {
        console.log(error || '消息发布成功');
        uni.showToast({ title: '消息发布成功', icon: 'success' });
      });
    } else {
      uni.showToast({ title: '发布消息为空', duration: 1000 });
    }
  }

  unsubscribe(topic) {
    this.client.unsubscribe(topic, (err) => {
      console.log(err || '取消订阅成功');
      uni.showToast({ title: '取消订阅成功', icon: 'success' });
    });
  }

  unconnect() {
    if (!this.client || !this.client.connected) {
      uni.showToast({ title: '客户端未连接', duration: 1000 });
      return;
    }
    this.client.end();
    this.client = null;
    uni.showToast({ title: '成功断开连接', icon: 'success' });
    console.log('断开连接');
    this.isConnected = false;
  }

  getHost() {
    let hosts = '';
    switch (process.env.VUE_APP_PLATFORM) {
      case 'APP-PLUS':
        hosts = 'tcp://IP:8083/mqtt'; // 需要替换为实际的 IP 地址
        break;
      case 'H5':
        hosts = 'wss://' + this.options.host + ':' + this.options.wssport + '/mqtt';
        break;
      case 'MP-WEIXIN':
        hosts = 'wxs://' + this.options.host + '/mqttwss';
        break;
      default:
        hosts = 'wss://' + this.options.host + ':' + this.options.wssport + '/mqtt';
    }
    return hosts;
  }
}

const mqttService = new MqttService();

export default mqttService;